package com.copyctrl.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.SystemConstants;
import com.copyctrl.campus.common.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author:JH
 * @version:1.0
 */
@Slf4j
@RestController
public class FileUploadController {

    @PostMapping("/pic")
    public ApiResponse uploadImage(@RequestParam("file") MultipartFile image) {
        try {
            // 获取原始文件名称
            String originalFilename = image.getOriginalFilename();
            // 生成新文件名
            String fileName = createNewFileName(originalFilename);
            // 保存文件
            File dest = new File(SystemConstants.IMAGE_UPLOAD_DIR, fileName);
            FileUtils.copyInputStreamToFile(image.getInputStream(),dest);
            // 返回结果
            log.debug("文件上传成功，{}", fileName);
            //放入删除的延迟队列 TODO 设计延时、死信队列
            //dataPublisher.deleteFile(fileName);
            return ApiResponse.ofSuccess(fileName);
        } catch (IOException e) {
            log.error("文件上传失败:"+e.getMessage());
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @DeleteMapping("/pic")
    public ApiResponse deleteBlogImg(@RequestBody String filename) {
        Map map = JSONUtil.toBean(filename, Map.class);
        File file = new File(SystemConstants.IMAGE_UPLOAD_DIR, map.get("fileName").toString());
        if (file.isDirectory()) {
            return ApiResponse.ofFailure("错误的文件名称");
        }
        FileUtil.del(file);
        //TODO 把文件路径从死信队列种删除
        return ApiResponse.ofSuccess(null);
    }

    @PostMapping("/dynamic")
    public ApiResponse uploadDynamicImage(@RequestParam("file") MultipartFile image) {
        try {
            // 获取原始文件名称
            String originalFilename = image.getOriginalFilename();
            // 生成新文件名
            String fileName = createNewFileName(originalFilename);
            // 保存文件
            image.transferTo(new File(SystemConstants.DYNAMIC_UPLOAD_DIR, fileName));
            // 返回结果
            log.debug("文件上传成功，{}", fileName);
            //放入删除的延迟队列 TODO 设计延时、死信队列
            //dataPublisher.deleteFile(fileName);
            return ApiResponse.ofSuccess(fileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @DeleteMapping("/dynamic")
    public ApiResponse deleteDynamicImg(@RequestBody String filename) {
        Map map = JSONUtil.toBean(filename, Map.class);
        File file = new File(SystemConstants.DYNAMIC_UPLOAD_DIR, map.get("fileName").toString());
        if (file.isDirectory()) {
            return ApiResponse.ofFailure("错误的文件名称");
        }
        FileUtil.del(file);
        //TODO 把文件路径从死信队列种删除
        return ApiResponse.ofSuccess(null);
    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        String name = UUID.randomUUID().toString();
        String fileName = StrUtil.removeAll(name, "-");
        // 生成文件名
        return StrUtil.format("{}.{}",  fileName, suffix);
    }
}
